# 设置项目目录路径、下载链接和文件夹名称
$projectDir = "."
$downloadUrl = "http://localhost:3000/download-devcontainer/$folderName"
$devcontainerZip = "$projectDir/devcontainer.zip"
$devcontainerDir = "$projectDir/.devcontainer"

function ConvertTo-Hex {
    param ([string]$inputString)
    $hexString = ""
    foreach ($char in $inputString.ToCharArray()) {
        $hexString += [convert]::ToString([int][char]$char, 16)
    }
    return $hexString
}

# 将十六进制字符串转换回原字符串
function ConvertFrom-Hex {
    param ([string]$hexString)
    $outputString = ""
    for ($i = 0; $i -lt $hexString.Length; $i += 2) {
        $outputString += [char][convert]::ToInt32($hexString.Substring($i, 2), 16)
    }
    return $outputString
}

# 检查 VSCode 是否安装
if (-not (Get-Command "code" -ErrorAction SilentlyContinue)) {
    Write-Error "Visual Studio Code is not installed or not in the system's PATH."
    Exit 1
}

# 检查 Docker Desktop 是否安装
if (-not (Get-Command "docker" -ErrorAction SilentlyContinue)) {
    Write-Error "Docker Desktop is not installed or not in the system's PATH."
    Exit 1
}

# 检查 devcontainer CLI 是否安装
if (-not (Get-Command "devcontainer" -ErrorAction SilentlyContinue)) {
    Write-Host "devcontainer CLI is not installed. Attempting to install..."

    # 安装 devcontainer CLI
    $installScript = "npm install -g @devcontainers/cli"

    try {
        Invoke-Expression $installScript
        Write-Host "devcontainer CLI installed successfully."
    } catch {
        Write-Error "Failed to install devcontainer CLI. Please check your npm installation and try again."
        Exit 1
    }
}

# 检查 Docker Desktop 是否启动
$dockerStatus = & docker info 2>$null
if ($dockerStatus -match "Cannot connect to the Docker daemon" -or -not $dockerStatus) {
    Write-Host "Docker Desktop is not running. Attempting to start Docker Desktop..."

    # 启动 Docker Desktop
    Start-Process -FilePath "C:\Program Files\Docker\Docker\Docker Desktop.exe"
    
    # 等待 Docker Desktop 启动完成（最长等待时间为5分钟）
    $maxRetries = 60
    $retries = 0
    while ($retries -lt $maxRetries) {
        Start-Sleep -Seconds 5
        $dockerStatus = & docker info 2>$null
        if ($dockerStatus -notmatch "Cannot connect to the Docker daemon" -and $dockerStatus) {
            Write-Host "Docker Desktop has started successfully."
            break
        }
        $retries++
    }
    
    if ($retries -eq $maxRetries) {
        Write-Error "Failed to start Docker Desktop. Please check your Docker installation."
        Exit 1
    }
}

# 如果所有工具都安装并且 Docker Desktop 已启动，则继续执行脚本
Set-Location -Path $projectDir

# 从服务器下载 .devcontainer 文件夹
Write-Host "Downloading .devcontainer from $downloadUrl..."
$webResponse = Invoke-WebRequest -Uri $downloadUrl -OutFile $devcontainerZip

# 检查下载是否成功
if (-Not (Test-Path $devcontainerZip)) {
    Write-Host "Download failed. Please check the URL and try again."
    exit 1
}

# 解压下载的文件
Write-Host "Extracting .devcontainer..."
try {
    Expand-Archive -Path $devcontainerZip -DestinationPath $devcontainerDir -Force
} catch {
    Write-Error "Extraction failed. Please check the ZIP file and try again."
    exit 1
}

# 删除下载的 zip 文件
Remove-Item -Path $devcontainerZip

# 启动开发容器并捕获输出
$output = devcontainer up --workspace-folder .

# 解析 JSON 输出并提取 Container ID
try {
    $json = $output | ConvertFrom-Json
    $containerId = $json.containerId

    # 截取 Container ID 的前12位
    $shortContainerId = $containerId.Substring(0, 12)

    # 打印截取后的 Container ID
    Write-Output "Short Container ID: $shortContainerId"

    # 将容器 ID 转换为十六进制表示
    $hexContainerId = ConvertTo-Hex $shortContainerId
    
    # 使用 VSCode 连接到容器
    Write-Output "使用 VSCode 连接到容器..."
    code --folder-uri "vscode-remote://attached-container+$hexContainerId/"
} catch {
    Write-Error "Failed to parse container output or connect to VSCode. Please check the devcontainer setup."
    exit 1
}


